package mt.dummy;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.LinkedList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import mt.Order;
import mt.client.MicroTraderClient;
import mt.comm.ClientComm;
import mt.comm.ClientSideMessage;
import mt.comm.ClientSideMessage.Type;

public class MicroTraderClientDummy implements MicroTraderClient {
	private JFrame frame;
	private JTextField txtAvailOrders;
	private JTextField txtOrderHistory;
	private ClientComm cliComm;
	private String nickname;
	private String txtToDisplay;
	private JTextArea txtOrders = new JTextArea();
	private LinkedList<Order> orderHistory = new LinkedList<Order>();


	@Override
	public void start(ClientComm clientComm) {
		this.cliComm = clientComm;

		nickname = JOptionPane.showInputDialog("Insert nickname");
		frame = new JFrame("Micro Trader");
		frame.setBounds(100, 100, 671, 431);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(new BorderLayout(0, 0));

		// 'Connect and Disconnect from Server' Buttons
		JButton btnLigar = new JButton("Connect to Server");
		btnLigar.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					String host = "127.0.0.1";
					cliComm.connect(host, nickname);
					if(cliComm.hasNextMessage()){
						ClientSideMessage msg = cliComm.getNextMessage();
						if(msg.getType() == Type.ORDER)
							txtToDisplay = txtToDisplay + "\n" + msg.getOrder().toString();
						else
							JOptionPane.showMessageDialog(null,	msg.getError());
					}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}
		});
		JButton btnDesligar = new JButton("Disconnect from Server");
		btnDesligar.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				cliComm.disconnect();				
			}
		});
		JPanel buttonsPanel = new JPanel();
		buttonsPanel.add(btnLigar);
		buttonsPanel.add(btnDesligar);

		// Available Orders
		JPanel availOrdersPanel = new JPanel();
		frame.getContentPane().add(availOrdersPanel, BorderLayout.CENTER);
		availOrdersPanel.setLayout(new BorderLayout(0, 0));
		txtAvailOrders = new JTextField();
		txtAvailOrders.setBackground(Color.LIGHT_GRAY);
		txtAvailOrders.setHorizontalAlignment(SwingConstants.CENTER);
		txtAvailOrders.setText("Available Orders");
		availOrdersPanel.add(txtAvailOrders, BorderLayout.NORTH);
		txtAvailOrders.setEditable(false);
		txtAvailOrders.setColumns(10);

		txtOrders.setTabSize(10);
		txtOrders.setText(txtToDisplay);
		availOrdersPanel.add(txtOrders, BorderLayout.CENTER);
		txtOrders.setEditable(false);

		// 'Update Available Orders' Button		
		JButton btnUpdate = new JButton("Update Available Orders");
		btnUpdate.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if(cliComm.isConnected()){
					if(cliComm.hasNextMessage()){
						ClientSideMessage msg = cliComm.getNextMessage();
						if(msg.getType() == Type.ORDER)
							txtToDisplay = txtToDisplay + "\n" + msg.getOrder().toString();
						else
							JOptionPane.showMessageDialog(null,	msg.getError());
					}
					txtOrders.setText(txtToDisplay);
					frame.repaint();
					frame.revalidate();
				}
			}
		});
		buttonsPanel.add(btnUpdate);
		frame.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);

		// Order History
		JPanel eastPanel = new JPanel();
		frame.getContentPane().add(eastPanel, BorderLayout.EAST);
		eastPanel.setLayout(new BorderLayout(0, 0));

		JPanel orderHistPanel = new JPanel();
		eastPanel.add(orderHistPanel, BorderLayout.NORTH);
		orderHistPanel.setLayout(new GridLayout(11, 1, 0, 0));

		txtOrderHistory = new JTextField();
		txtOrderHistory.setText(nickname+"'s Order History");
		orderHistPanel.add(txtOrderHistory);
		txtOrderHistory.setColumns(10);
		txtOrderHistory.setEditable(false);

		displayOrderHistory(frame);

		// 'Submit Order' Buttons
		JPanel submitButtonsPanel = new JPanel();
		submitButtonsPanel.setLayout(new GridLayout(2,0));
		JPanel panel1 = new JPanel();
		JButton btnSubmitBuyOrder = new JButton("Submit Buy Order");
		btnSubmitBuyOrder.addActionListener(new ActionListener() {

			private JFrame newWindow = new JFrame("Submit Buy Order");
			private JTextField txtStock = new JTextField();
			private JTextField txtUnits = new JTextField();
			private JTextField txtPrice = new JTextField();

			@Override
			public void actionPerformed(ActionEvent e) {
				if(cliComm.isConnected()){
					newWindow.setSize(300, 300);
					newWindow.setLocation(700, 100);
					JPanel fields = new JPanel();
					fields.setLayout(new GridLayout(7,0));
					JLabel lblStock = new JLabel("Stock name:");
					fields.add(lblStock);
					fields.add(txtStock);
					JLabel lblUnits = new JLabel("Number of units:");
					fields.add(lblUnits);
					fields.add(txtUnits);
					JLabel lblPrice = new JLabel("Price per unit:");
					fields.add(lblPrice);
					fields.add(txtPrice);
					newWindow.add(fields, BorderLayout.CENTER);
					JPanel btnPanel = new JPanel();
					JButton btnConfirm = new JButton("Submit Order");
					btnConfirm.addActionListener(new ActionListener() {

						@Override
						public void actionPerformed(ActionEvent e) {
							String stock = txtStock.getText();
							int numberOfUnits = Integer.parseInt(txtUnits.getText().trim());
							double pricePerUnit = Double.parseDouble(txtPrice.getText().trim());	
							Order order = Order.createBuyOrder(nickname, stock, numberOfUnits, pricePerUnit);
							cliComm.sendOrder(order);
							orderHistory.add(order);
							displayOrderHistory(frame);
							newWindow.dispose();						
						}

					});
					btnPanel.add(btnConfirm);
					newWindow.add(btnPanel, BorderLayout.SOUTH);

					newWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
					newWindow.setVisible(true);
				}
			}
		});
		panel1.add(btnSubmitBuyOrder);
		JPanel panel2 = new JPanel();
		JButton btnSubmitSellOrder = new JButton("Submit Sell Order");
		btnSubmitSellOrder.addActionListener(new ActionListener() {

			private JFrame newWindow = new JFrame("Submit Sell Order");
			private JTextField txtStock = new JTextField();
			private JTextField txtUnits = new JTextField();
			private JTextField txtPrice = new JTextField();

			@Override
			public void actionPerformed(ActionEvent e) {
				if(cliComm.isConnected()){
					newWindow.setSize(300, 300);
					newWindow.setLocation(700, 100);
					JPanel fields = new JPanel();
					fields.setLayout(new GridLayout(7,0));
					JLabel lblStock = new JLabel("Stock name:");
					fields.add(lblStock);
					fields.add(txtStock);
					JLabel lblUnits = new JLabel("Number of units:");
					fields.add(lblUnits);
					fields.add(txtUnits);
					JLabel lblPrice = new JLabel("Price per unit:");
					fields.add(lblPrice);
					fields.add(txtPrice);
					newWindow.add(fields, BorderLayout.CENTER);
					JPanel btnPanel = new JPanel();
					JButton btnConfirm = new JButton("Submit Order");
					btnConfirm.addActionListener(new ActionListener() {

						@Override
						public void actionPerformed(ActionEvent e) {
							String stock = txtStock.getText();
							int numberOfUnits = Integer.parseInt(txtUnits.getText().trim());
							double pricePerUnit = Double.parseDouble(txtPrice.getText().trim());	
							Order order = Order.createSellOrder(nickname, stock, numberOfUnits, pricePerUnit);
							cliComm.sendOrder(order);
							orderHistory.add(order);
							displayOrderHistory(frame);
							newWindow.dispose();						
						}

					});
					btnPanel.add(btnConfirm);
					newWindow.add(btnPanel, BorderLayout.SOUTH);

					newWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
					newWindow.setVisible(true);
				}
			}
		});
		panel2.add(btnSubmitSellOrder);
		submitButtonsPanel.add(panel1);
		submitButtonsPanel.add(panel2);
		eastPanel.add(submitButtonsPanel, BorderLayout.SOUTH);
		frame.setVisible(true);
	}

	private void displayOrderHistory(JFrame f){
		if(!orderHistory.isEmpty()){
			String history = txtOrderHistory.getText();
			for(int i = 0; i < orderHistory.size(); i++){
				history = history + "\n" + orderHistory.get(i).toString();
			}
		}
		f.repaint();
		f.revalidate();
	}

}
